<script setup>
import carBrandService from '@/api/modules/carBand.js'
import carModelService from '@/api/modules/carmodel.js'
import ordersService from '@/api/modules/ordersService.js'
import productService from '@/api/modules/product.js'
import shoppingCartService from '@/api/modules/shoppingcart.js'
import Stepper from '@/components/Stepper/Stepper.vue'
import SuccessOrders from '@/components/SuccessOrders/SuccessOrders.vue'
import SvgIcon from '@/components/SvgIcon/SvgIcon.vue'
import useAppStore from '@/store/modules/app.js'
import { useUserStore } from '@/store/modules/user.js'
import { getToken } from '@/utils/auth.js'
import {
  deepClone,
  getLocalBrandName,
  getLocalCareModelName,
  getLocalImageUrl,
  getLocalProductName,
  setImgUrl,
} from '@/utils/index.js'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'

const { t } = useI18n()
const userStore = useUserStore()
const appStore = useAppStore()
const desShowAll = ref(false)
const pageParams = ref({
  pageNum: 1,
  pageSize: 15,
})
const pageTotal = ref(0)
const carBrandRef = ref(null)
const carBrandList = ref([])
const carBrandType = ref('')

const productName = ref('')

const carList = ref([])

const route = useRoute()

const showModal = ref(false)
const showSureOrders = ref(false)

const shopType = ref('')
const shopDetail = ref({})
const cartPrice = ref(0)
const carModelList = ref([])
const carModeId = ref('')

watch(
  () => route.query.keyword,
  (newKeyword) => {
    productName.value = newKeyword || ''
    getCarList()
  },
  { immediate: true }, // 首次加载也执行
)
onMounted(() => {
  getCarBrand()
  getCarList()
})

function getCarBrand() {
  const params = {
    pageNum: 1,
    pageSize: 99999999,
    delFlag: '0',
  }
  carBrandService.list(params).then((res) => {
    const data = res?.rows
    if (data.length > 0) {
      carBrandList.value = res?.rows
      carBrandList.value.unshift({
        id: 0,
        brand: '全部',
        brandIcon: getLocalImageUrl('all.png'),
      })
      carBrandType.value = carBrandList.value[0].brand
    }
  })
}

function getCarList() {
  const params = {
    ...pageParams.value,
    delFlag: '0',
    remark2: carBrandType.value === '全部' ? null : carBrandType.value,
    status: '0',
    productName: productName.value === '' ? null : productName.value,
    vehicleModel: carModeId.value === '' ? null : carModeId.value,
  }
  productService.list(params).then((res) => {
    carList.value = res?.rows
    pageTotal.value = res?.total
  }).finally(() => {
  })
}

function getCarModel() {
  carModelService.list({
    pageNum: 1,
    pageSize: 99999999,
    delFlag: '0',
    brand: carBrandType.value,
  }).then((res) => {
    carModelList.value = res?.data
  })
}
function handleCarBrandChange(brand) {
  carBrandType.value = brand
  pageParams.value.pageNum = 1
  carModeId.value = ''
  getCarList()
  getCarModel()
}

function handleToggleShow() {
  desShowAll.value = !desShowAll.value
}

function handleShowModal(type, item) {
  showModal.value = true
  shopType.value = type
  shopDetail.value = item
  shopDetail.value.productName = getLocalProductName(item)
  cartPrice.value = item.sellingPrice1
  if (item.productImage) {
    shopDetail.value.imgList = item.productImage.split(',')
  }
}

function handleStepperChange(value) {
  const price = shopDetail.value.sellingPrice1 * value
  shopDetail.value.count = value
  cartPrice.value = price
}

function handleCarModelChange(id) {
  carModeId.value = id
  pageParams.value.pageNum = 1
  getCarList()
}

function handlePageChange(pageNum) {
  pageParams.value.pageNum = pageNum
  getCarList()
}

function handleCheckoutOrder() {
  const token = getToken()
  if (!token) {
    window.$dialog.warning({
      title: t('SystemPrompts'),
      type: 'warning',
      content: t('message.notLoggedInMessage'),
      onOk: () => {
      },
    })
    return
  }
  const type = shopType.value
  const params = deepClone(shopDetail.value)
  if (type === 'car') {
    params.unitPrice = shopDetail.value.sellingPrice1
    params.createBy = userStore.userInfo.nickName
    params.quantity = shopDetail.value.count || 1
    delete params.imgList
    delete params.count
    shoppingCartService.add(params).then((res) => {
      window.$message.success(t('message.addCartSuccess'))
      // message.success(t('message.addCartSuccess'))
      // appStore.setCartsCount(shopDetail.value.count + appStore.cartsCount)
      // handleHideModal()
      showModal.value = false
    })
  }
  else {
    const data = {
      id: params.id,
      totalQuantity: params.count || 1,
    }
    ordersService.addCustomerOrder(data).then((res) => {
      showSureOrders.value = true
    })
  }
  handleHideModal()
}

function handleHideModal() {
  shopDetail.value.count = 1
  showModal.value = false
}
</script>

<template>
  <div class="container mx-auto px-4 sm:px-6 lg:px-8 space-y-4">
    <n-card :bordered="false">
      <div class="car-filter relative flex items-center">
        <div class="w-13 text-[14px] text-gray-400 dark:text-gray-300 tracking-wider min-w-[69px]">
          {{ t('brand') }}：
        </div>
        <ul
          ref="carBrandRef" class="grid grid-cols-15 w-full gap-2 overflow-hidden transition-all duration-600 ease-in-out"
          :class="desShowAll ? 'max-h-screen' : 'max-h-20 '"
        >
          <li
            v-for="item in carBrandList" :key="item.id" class="car-item p-1.5 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-md"
            :class="{
              'bg-gray-100 dark:bg-gray-800 rounded-md': carBrandType === item.brand,
            }"
            @click="handleCarBrandChange(item.brand)"
          >
            <div class="flex items-center justify-center">
              <div v-if="item.id > 0" class="h-[30px] w-[55px]">
                <n-image
                  :src="setImgUrl(item.brandIcon)"
                  class="h-full w-full object-cover"
                  alt="productImage"
                >
                  <template #error>
                    <div class="flex items-center justify-center h-full w-full text-gray-400">
                      <SvgIcon name="lets-icons:img-box-light" class="text-[30px]" />
                    </div>
                  </template>
                </n-image>
              </div>
              <img v-else src="@/assets/img/all.png" alt="" class="h-[27px] w-[27px]">
            </div>
            <div class="line-clamp-1 mt-1 overflow-hidden text-ellipsis text-center mt-1">
              {{ getLocalBrandName(item) }}
            </div>
          </li>
        </ul>
        <n-button
          v-if="carBrandList.length > 14"
          quaternary
          class="text-brand-dark hover:text-brand relative top-10"
          @click="handleToggleShow"
        >
          <template #icon>
            <SvgIcon v-if="desShowAll" name="icon-park-outline:up" />
            <SvgIcon v-else name="icon-park-outline:down" />
          </template>
          {{ desShowAll ? t('collapse') : t('expand') }}
        </n-button>
      </div>
      <div v-if="carBrandType !== '全部'" class="car-filter mt-5 flex items-center border-t border-t-[#dedede] border-dashed pt-[15px]">
        <span class="text-[14px] text-gray-400 dark:text-gray-300 tracking-wider min-w-[69px]">类型：</span>
        <ul class="ml-[5px] flex transform items-center duration-300 space-x-5">
          <li
            v-for="item in carModelList" :key="item.id" class="cursor-pointer rounded px-1.5 py-1 text-[13px] transition-colors duration-300  hover:bg-gray-100 dark:hover:bg-gray-800"
            :class="{
              'bg-gray-100 dark:bg-gray-800 rounded-md': carModeId === item.modelZh,
            }"

            @click="handleCarModelChange(item.modelZh)"
          >
            <span>
              {{ getLocalCareModelName(item) }}
            </span>
          </li>
        </ul>
      </div>
    </n-card>
    <n-card :bordered="false">
      <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6">
        <div
          v-for="item in carList"
          :key="item.id"
          class="car-list-item cursor-pointer rounded-md bg-[#F7FAFE] dark:bg-[#2E3138] pb-2 space-y-3 transition-all duration-300 ease-in-out hover:shadow-lg"
          @click="handleShowModal('car', item)"
        >
          <div class="h-60 w-full">
            <n-image
              :src="setImgUrl(item.productImage)"
              class="h-full w-full object-cover"
              alt="productImage"
            >
              <template #error>
                <div class="flex items-center justify-center h-full w-full text-gray-400">
                  <SvgIcon name="lets-icons:img-box-light" class="text-[50px]" />
                </div>
              </template>
            </n-image>
          </div>
          <div class="car-list-title line-clamp-2 h-13 overflow-hidden text-ellipsis px-3 text-xl font-medium leading-tight">
            {{ getLocalProductName(item) }}
          </div>
          <div class="car-list-config px-3 text-gray-400 dark:text-gray-300 space-y-1">
            <div class="car-list-partNumber">
              {{ t('shopList.partNumber') }}：{{ item.productNumber }}
            </div>
            <div class="car-list-specs">
              {{ t('shopList.specs') }}：{{ item.productSpecification }}
            </div>
            <div class="car-list-weight">
              {{ t('shopList.weight') }}：{{ item.productWeight }}kg
            </div>
          </div>
          <div class="car-list-buy flex items-center justify-between px-3">
            <div class="car-list-price text-2xl text-red-500 font-bold">
              <span class="mr-1 font-bold">¥</span>
              <span class="font-number text-3xl font-bold">{{ item.sellingPrice1 }}</span>
            </div>
            <div class="car-list-cart">
              <n-button-group>
                <n-button strong secondary type="info" @click="handleShowModal('car', item)">
                  <SvgIcon name="akar-icons:cart" class="text-xl cursor-pointer" />
                </n-button>
                <n-button type="info" @click.stop="handleShowModal('buy', item)">
                  {{ t('shopList.toBuy') }}
                </n-button>
              </n-button-group>
            </div>
          </div>
        </div>
      </div>
      <div class="mt-5 flex justify-center ">
        <n-pagination
          v-if="pageTotal > 15"
          v-model:page="pageParams.pageNum"
          v-model:page-size="pageParams.pageSize"
          :item-count="pageTotal"
          simple
          @update:page="handlePageChange"
        />
      </div>
    </n-card>
    <n-modal
      v-model:show="showModal"
      class="!w-full !max-w-4xl"
    >
      <n-card :bordered="false" content-class="!p-0 !pr-4">
        <div class="grid grid-cols-1 md:grid-cols-2">
          <div class="relative bg-zinc-100 p-6 rounded-md dark:bg-zinc-800" />
          <div class="p-6 space-y-6">
            <div class="flex flex-col space-y-1.5 text-center sm:text-left">
              <div class="text-2xl font-semibold">
                {{ shopDetail.productName }}
              </div>
            </div>
            <div class="flex flex-wrap gap-2">
              <n-button strong secondary round type="info" size="small">
                {{ t('shopList.partNumber') }}：{{ shopDetail.productNumber }}
              </n-button>
              <n-button strong secondary round type="info" size="small">
                {{ t('shopList.specs') }}：{{ shopDetail.productSpecification }}
              </n-button>
              <n-button strong secondary round type="info" size="small">
                {{ t('shopList.weight') }}：{{ shopDetail.productWeight }}
              </n-button>
            </div>
            <div>
              <div class="text-3xl font-bold text-red-500">
                ¥ {{ shopDetail.sellingPrice1 }}
              </div>
            </div>
            <div class="space-y-2">
              <label for="quantity" class="text-sm font-medium">
                {{ t('quantity') }}：
              </label>
              <div class="flex items-center space-x-2">
                <Stepper :value="shopDetail.count" @change="handleStepperChange" />
              </div>
            </div>
            <div data-orientation="horizontal" role="none" class="shrink-0 bg-border h-[1px] w-full bg-gray-200 dark:bg-gray-700" />
            <div class="flex items-center justify-between">
              <span class="font-medium">{{ t('totalPrice') }}：</span>
              <span class="text-xl font-bold text-red-500">¥ {{ cartPrice }}</span>
            </div>
            <div class="flex gap-4 pt-4">
              <n-button class="w-[50%]" @click="showModal = false">
                {{ t('shopList.cancel') }}
              </n-button>
              <n-button type="primary" class="w-[50%]" @click="handleCheckoutOrder">
                {{ shopType === 'buy' ? t('shopList.submit') : t('shopList.addCart') }}
              </n-button>
            </div>
          </div>
        </div>
      </n-card>
    </n-modal>

    <SuccessOrders v-model:visible="showSureOrders" />
  </div>
</template>

<style lang="scss" scoped>
.car-item {
  text-align: center;
  letter-spacing: 1px;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 68px;
  max-height: 70px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
</style>
